import { createRouter, createWebHashHistory, type RouteLocationNormalized } from 'vue-router'
import { createDiscreteApi } from 'naive-ui'
import routes from './routes'
import { usePermissionStore } from '@/stores/permission'
import { getToken } from '@/utils/auth'
import { useTagStore } from '@/stores/layout'
import { toRaw } from 'vue'

const router = createRouter({
  history: createWebHashHistory(import.meta.env.BASE_URL),
  routes
})
export default router

/**
 *
 * Features
 * - 设置`document.title`
 * - 开始进度条
 * - 检查 `token和白名单`
 * - 登陆页面需要清理干净 `路由、按钮权限、侧边栏、token`
 * - 其它页面都需要检查 `路由`，`侧边栏、按钮权限、路由`都是同一个接口，所以更新路由的时候会一起更新掉其它
 *
 */
router.beforeEach(async (to, _, next) => {
  handleTo()

  // 权限、路由操作
  if (whiteList.includes(to.name as string)) return next()
  const token = getToken()
  const store = usePermissionStore()
  if (token && to.name === 'login') return next('/')
  if (to.name === 'login') {
    store.removeRoutes()
    store.removeUserInfo()
    store.setLayoutRouteRedirect()
    return next()
  }

  handleRouteToDetail(to)

  if (token && !store.routes.length) {
    await store.addRoutes()

    if (store.hrefRedirect) {
      window.location.href = store.hrefRedirect
      return next(false)
    }

    if (!store.routes.length) {
      alert('没有分配权限，请联系管理员!')
      return next(false)
    }

    return next({ ...to, replace: true })
  }
  if (!token) {
    return next({ name: 'login', query: { redirect: to.fullPath } })
  }

  next()
})

/**
 *
 * Features
 * - 结束进度条
 *
 */
router.afterEach(() => {
  loadingBar.finish()
})

const whiteList = ['401']
const handleTo = () => {
  // setTitle(to)
  loadingBar.start()
}
const { loadingBar } = createDiscreteApi(['loadingBar'], {
  loadingBarProviderProps: {
    themeOverrides: {
      colorLoading: '#3B3B98'
    }
  }
})

/**
 * 修复详情页跳转存在缓存问题
 *
 * 描述：
 *    详情页跳转时，如果是同一个页面，会存在缓存问题，所以需要在跳转时，清除缓存
 *
 * 解决：
 *    1. 获取`tags`列表
 *    2. 查找`tags`列表中`tag.meta.title`与当前`to.meta.title`相等的`tag`
 *    3. 如果存在，删除当前`tag`
 */
function handleRouteToDetail(to: RouteLocationNormalized) {
  if (!to.meta.title?.includes('详情')) return

  const { tags } = useTagStore()
  const index = tags.findIndex((e) => e.meta.title === to.meta.title)
  if (index !== -1) {
    console.log('target', toRaw(tags[index]))
    tags.splice(index, 1)
  }
}
